package Negocio;

import java.sql.*;
import java.util.Map;
import java.util.Map.Entry;
import java.util.logging.*;

/**
 *
 * @author sabidosan, ...
 */
public class AdminDB {

    //@Resource(name = "jdbc/dbBYS")
    //DataSource ds;

    public AdminDB(){
    }
    
    public Connection getConnection() throws SQLException{
        
        String connURL= "jdbc:mysql://localhost:3306/bysDB";
        Connection conn = DriverManager.getConnection(connURL,"bys-dba","password");
        
        return conn;
        
        //return ds.getConnection();
    }

    public Integer getID(String tabla, String condicion){
    
       int id = 0;
       try
       {
           Connection conn = this.getConnection();
           Statement stmt = conn.createStatement();

           ResultSet rset = stmt.executeQuery("SELECT ID FROM `bysDB`.`"+tabla+"` WHERE "+condicion);
           
           if (rset.next()){ id = rset.getInt("ID"); }
           
           if(rset != null) rset.close();
           if(stmt != null) stmt.close();
           if(conn != null) conn.close();

        } catch (Exception e) {
            Logger.getLogger("Recuperar ID").log(Level.SEVERE, "ERROR: " + e.getLocalizedMessage());
        }
       finally {
           return id;
        }
    }
    
    public void borrarFila(String tabla, String condicion){    
        try
       {    
           Connection conn = this.getConnection();
           Statement stmt = conn.createStatement();

           stmt.executeUpdate("DELETE FROM `bysDB`.`"+tabla+"` WHERE "+condicion);

           if (stmt != null) stmt.close();
           if (conn != null) conn.close();

        } catch (Exception e) {
            Logger.getLogger("BorrarFila").log(Level.SEVERE, "ERROR: " + e.getLocalizedMessage());
        }
    }

    public boolean guardar(ObjetoDB o) {
       try
       {
           Connection conn = this.getConnection();
           Statement stmt = conn.createStatement();
           
           String sentencia = "INSERT INTO `bysDB`.`"+o.getTabla()+"` (";
           String values = ") VALUES (";
           
           boolean first = true;
           for (Map.Entry<String, String> entry : o.getCampos().entrySet()) {               
               if(first){
                   sentencia += "`"+entry.getKey()+"`";
                   values += "'"+entry.getValue()+"'";
                   first = false;
               }
               else if (o.getCampos().keySet().iterator().hasNext()){
                sentencia += ",`"+entry.getKey()+"`";
                values += ",'"+entry.getValue()+"'";
               }
            }           
           sentencia += values +");";

           stmt.executeUpdate(sentencia);

           if (stmt != null) stmt.close();
           if (conn != null)conn.close();

           return true;

        } catch (Exception e) {
            Logger.getLogger("Guardado en "+o.getTabla()).log(Level.SEVERE, "ERROR: " + e.getLocalizedMessage());
            return false;
        }
    }
    
    public boolean actualizar(ObjetoDB o) {
       try
       {
           Connection conn = this.getConnection();
           Statement stmt = conn.createStatement();
           
           String sentencia = "UPDATE `bysDB`.`"+o.getTabla()+"` SET ";
           String where = " WHERE ";
           
           boolean first = true;
           for (Map.Entry<String, String> entry : o.getCampos().entrySet()) {               
               if(first){
                   sentencia += entry.getKey()+"='"+entry.getValue()+"'";
                   where += "ID="+o.getId();
                   first = false;
               }
               else if (o.getCampos().keySet().iterator().hasNext()){
                sentencia += ","+entry.getKey()+"='"+entry.getValue()+"'";
               }
            }           
           sentencia += where;
           stmt.executeUpdate(sentencia);

           if (stmt != null) stmt.close();
           if (conn != null)conn.close();

           return true;

        } catch (Exception e) {
            Logger.getLogger("Actualizado "+o.getTabla()).log(Level.SEVERE, "ERROR: " + e.getLocalizedMessage());
            return false;
        }
    }
    
    public boolean borrar(ObjetoDB o) {
       try
       {
           Connection conn = this.getConnection();
           Statement stmt = conn.createStatement();
           
           String sentencia = "DELETE FROM `bysDB`.`"+o.getTabla()+"` WHERE ";
           
           boolean first = true;
           for (Map.Entry<String, String> entry : o.getCampos().entrySet()) {               
               if(first){
                   sentencia += entry.getKey()+"='"+entry.getValue()+"'";
                   first = false;
               }
               else if (o.getCampos().keySet().iterator().hasNext()){
                sentencia += " AND "+entry.getKey()+"='"+entry.getValue()+"'";
               }
            }
           stmt.executeUpdate(sentencia);

           if (stmt != null) stmt.close();
           if (conn != null)conn.close();

           return true;

        } catch (Exception e) {
            Logger.getLogger("Borrado "+o.getTabla()).log(Level.SEVERE, "ERROR: " + e.getLocalizedMessage());
            return false;
        }
    }
    
}
